#include <QCoreApplication>
#include <QTcpServer>
#include <QTcpSocket>
#include <QJsonDocument>
#include <QJsonObject>
#include <QDebug>
#include <QTimer>

class AIServer : public QTcpServer
{
    Q_OBJECT
public:
    AIServer(QObject *parent = nullptr) : QTcpServer(parent) {}

protected:
    void incomingConnection(qintptr socketDescriptor) override
    {
        qDebug() << "检测到新的客户端连接！";
        QTcpSocket *client = new QTcpSocket(this);
        client->setSocketDescriptor(socketDescriptor);

        connect(client, &QTcpSocket::readyRead, this, [client,this]() {
            // 读取客户端发来的所有数据
            QByteArray data = client->readAll();
            qDebug() << "收到客户端数据:" << data;

            // 简单的JSON解析
            QJsonDocument doc = QJsonDocument::fromJson(data);
            if (doc.isObject()) {
                QJsonObject obj = doc.object();
                if (obj["type"] == "translate")
                {
                    qDebug() << "请求类型：翻译。准备流式返回...";
                    // 模拟AI流式返回
                    streamResponse(client, obj["data"].toString());
                }
                else if (obj["type"] == "new_chat")
                {
                    qDebug() << "请求类型：新对话。已重置上下文。";
                    // 在这里，队友的真实代码会清空对话历史
                }
            }
        });

        connect(client, &QTcpSocket::disconnected, this, [client]() {
            qDebug() << "客户端已断开连接。";
            client->deleteLater();
        });
    }

private:
    void streamResponse(QTcpSocket *client, const QString &ocrText)
    {
        // 模拟的Markdown返回内容
        QString responseMarkdown = QString(
                                       "### 翻译结果 (模拟)\n\n"
                                       "这是对您发送的OCR文本的模拟翻译：\n\n"
                                       "> %1\n\n"
                                       "$$E=mc^2$$\n\n"
                                       "翻译完成！"
                                       ).arg(ocrText.left(50) + "..."); // 只显示前50个字符作为引述

        // 将完整的Markdown拆分成多个小片段
        int chunkSize = 10; // 每次发送10个字符
        for (int i = 0; i < responseMarkdown.length(); i += chunkSize)
        {
            QString chunk = responseMarkdown.mid(i, chunkSize);
            // 使用QTimer来模拟流式发送的时间间隔
            QTimer::singleShot(100 * (i / chunkSize), client, [client, chunk]()
            {
                if (client->state() == QAbstractSocket::ConnectedState)
                {
                    client->write(chunk.toUtf8());
                    qDebug() << "已发送片段:" << chunk;
                }
            });
        }
    }
};

#include "main.moc"

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    AIServer server;
    if (!server.listen(QHostAddress::Any, 8504)) { // 监听 8504 端口
        qDebug() << "服务器启动失败:" << server.errorString();
        return 1;
    }
    qDebug() << "AI 模拟服务器已启动，正在监听端口 8504...";

    return a.exec();
}
